package com.hao.tool.util.component.interceptor;

import com.hao.tool.common.constant.Commons;
import com.hao.tool.common.security.JwtConstant;
import com.hao.tool.common.security.JwtUtil;
import com.hao.tool.common.util.NetworkUtil;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by haol on 2017/3/15.
 */
@Component
public class WebInterceptor extends HandlerInterceptorAdapter {


    public WebInterceptor() {

    }

    Logger logger = LoggerFactory.getLogger(WebInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        String subject = null;

        try {
            String token = JwtUtil.getTokenValueByCookie(request, JwtConstant.COOKIE_NAME);
            Claims claims = JwtUtil.analyzeAndGetJWT(token);
            subject = claims.getSubject();
            request.setAttribute(Commons.SUB_KEY, subject);
            logger.info("用户 【{}】 在 {} 尝试访问：{}", subject,
                    NetworkUtil.getIpAddress(request), request.getRequestURI());
        } catch (Exception e) {
//            logger.warn("当前用户访问「{}」 （{}）", request.getRequestURI(), e.getMessage());
        }
        return true;
    }
}